package
{
	import flashx.textLayout.elements.OverflowPolicy;
	
	import org.flixel.*;
	import org.flixel.FlxText;
	import org.flixel.FlxTilemap;
	
	import zones.*;
	
	public class GameState extends FlxState
	{
		private var currentZone:Zone;
		private var player:Player;
		private var collidedDoor:Door;
		
		override public function create():void
		{
			super.create();
			currentZone = new ZoneTest2();
			add(currentZone);
			player = new Player();
			add(player);
			player.y = 50;
			FlxG.bgColor = 0xffff0000;
			FlxG.camera.follow(player,FlxCamera.STYLE_TOPDOWN);
			FlxG.worldBounds = new FlxRect(0,0,currentZone.width,currentZone.height);
			for(var i:int = 0;i<currentZone.doors.length;i++)
			{
				add(new FlxText(50,50+i*20,100,currentZone.doors.members[i].height+" "+currentZone.doors.members[i].zoneID));
			}
		}
		
		public function SetNewZone(door:Door):void
		{
			//Saves the id of the old door, so we can find the door it leads to
			var doorID:int = door.zoneID;
			var doorDirection:String = ZoneRegistry.GetDirectionFromID(door.zoneID);
			switch(doorDirection)
			{
				case "Left":doorID+=4;break;
				case "Right":doorID-=4;break;
				case "Up":doorID+=5;break;
				case "Down":doorID-=5;break;
			}
			//Sets the new zone
			remove(currentZone);
			currentZone = new door.toZoneClass();
			add(currentZone);
			
			//Finds the new position of the player by finding the corresponding door in the new room
			var newPlayerPos:FlxPoint = new FlxPoint(0,0);
			for(var i:int;i<currentZone.doors.length;i++)
			{
				if(Door(currentZone.doors.members[i]).zoneID == doorID)
				{
					player.x = Door(currentZone.doors.members[i]).x;
					player.y = Door(currentZone.doors.members[i]).y;
					
					//Setting the player position correctly according to what direction it came from
					switch(doorDirection)
					{
						case "Left":player.x+=16;break;
						case "Right":player.x-=32;break;
						case "Up":player.y-=64;break;
						case "Down":player.y+=16;break;
					}
				}
			}
			FlxG.camera.follow(player,FlxCamera.STYLE_TOPDOWN);
			FlxG.worldBounds = new FlxRect(0,0,currentZone.width,currentZone.height);
		}
		override public function update():void
		{
			super.update();
			FlxG.collide(player,currentZone.walkableTiles);
			if(collidedDoor == null)
			{
				FlxG.overlap(player,currentZone.doors,checkDoorCollision);
			}
			else if(!player.autoMoving)
			{
				SetNewZone(collidedDoor);
				collidedDoor = null;
			}
		}
		private function checkDoorCollision(player:FlxObject,door:FlxObject):void
		{
			collidedDoor = Door(door);
			switch(ZoneRegistry.GetDirectionFromID(collidedDoor.zoneID))
			{
				case "Left":this.player.setMovement(-16,0);break;
				case "Right":this.player.setMovement(16,0);break;
				case "Up":this.player.setMovement(0,-16);break;
				case "Down":this.player.setMovement(0,16);break;
			}
		}
	}
}